<template>
  <div class="list-table">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('客户全称')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('客户全称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('客户类型')" prop="type">
        <el-select v-model="queryParams.type" value="" :placeholder="$t('客户类型')" clearable>
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('关注等级')" prop="followLevel">
        <el-select v-model="queryParams.followLevel" value="" :placeholder="$t('关注等级')" clearable>
          <el-option
            v-for="dict in followLeve"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('是否开通账号')" prop="accountOpen">
        <el-select v-model="queryParams.accountOpen" value="" :placeholder="$t('是否开通账号')" clearable>
          <el-option :label="$t('是')" value="Y" />
          <el-option :label="$t('否')" value="N" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>
    <el-row v-if="code === 'now'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="code === 'now'"
          v-hasPermi="['lp:base:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandleNow"
        >{{ $t("导出") }}</el-button>
      </el-col>
    </el-row>
    <el-row v-if="code !== 'now'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['lp:base:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col v-if="code === 'all'" :span="1.5">
        <el-button
          v-hasPermi="['lp:base:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['lp:base:edit']"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="upload.open = true"
        >{{ $t("导入") }}</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      tooltip-effect="darkTable"
      :data="lpBaseList"
      border
      class="noneHoverBg"
    >
      <div>
        <el-table-column :label="$t('客户全称')" fixed align="center" prop="name" :show-overflow-tooltip="true" min-width="200">
          <template slot-scope="scope">
            <router-link
              target="_blank"
              :to="{path:'/fund/lpBase/lpBaseHome',query:{lpId:scope.row.id}}"
              class="link_a"
            >{{ scope.row.name }}</router-link>
          </template>
        </el-table-column>
        <el-table-column v-if="code === 'all'" :label="$t('客户状态')" align="center" prop="status" width="120" />
        <el-table-column :label="$t('联系电话')" align="center" prop="phone" width="120" />
        <el-table-column :label="$t('客户邮箱')" show-overflow-tooltip align="center" prop="email" width="200" />
        <el-table-column :label="$t('投资偏好')" align="center" prop="preference" show-overflow-tooltip width="200" />
        <el-table-column :label="$t('历史投资')" align="center" prop="hisInvestment" show-overflow-tooltip width="200" />
      </div>
      <div v-if="code === 'now'">
        <el-table-column v-if="code === 'now'" :label="$t('认缴基金')" prop="fundName" align="center" width="200">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.fundInfoMap" :key="new Date().getTime() + '_' + index" class="multi-table-td" :class="scope.row.fundInfoMap.length === 1 ? 'noStyle' : ''">
              <div :title="item.fundName">{{ item.fundName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="code === 'now'" :label="$t('认缴金额') + $t('金额单位')" prop="subscribedAmount" align="center" width="100">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.fundInfoMap" :key="new Date().getTime() + '_' + index" class="multi-table-td" :class="scope.row.fundInfoMap.length === 1 ? 'noStyle' : ''">
              <div>{{ moneyFormat(item.subscribedAmount, 'w') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="code === 'now'" :label="$t('认缴比例(%)')" prop="subscriptionRatio" align="center" width="100">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.fundInfoMap" :key="new Date().getTime() + '_' + index" class="multi-table-td" :class="scope.row.fundInfoMap.length === 1 ? 'noStyle' : ''">
              <div>{{ moneyFormat(item.subscriptionRatio) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="code === 'now'" :label="$t('实缴金额') + $t('金额单位')" prop="paidAmount" align="center" width="100">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.fundInfoMap" :key="new Date().getTime() + '_' + index" class="multi-table-td" :class="scope.row.fundInfoMap.length === 1 ? 'noStyle' : ''">
              <div>{{ moneyFormat(item.paidAmount, 'w') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="code === 'now'" :label="$t('缴款比例(%)')" prop="paidRatio" align="center" width="100">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.fundInfoMap" :key="new Date().getTime() + '_' + index" class="multi-table-td" :class="scope.row.fundInfoMap.length === 1 ? 'noStyle' : ''">
              <div>{{ moneyFormat(item.paidRatio) }}</div>
            </div>
          </template>
        </el-table-column>
        <!--
        <el-table-column v-if="code === 'now'" :label="$t('已分金额') + $t('金额单位')" prop="paidAmount" align="center" show-overflow-tooltip width="100">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.allocatedAmount, 'w') }}</span>
          </template>
        </el-table-column>
        -->
      </div>
      <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="190">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['lp:base:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['lp:base:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
          <el-button
            v-hasPermi="['lp:base:open']"
            size="small"
            type="text"
            icon="el-icon-user"
            @click="openAnAccount(scope.row)"
          >{{ $t('账号') }}</el-button>
          <!--<el-button-->
          <!--  v-hasPermi="['lp:base:close']"-->
          <!--  size="small"-->
          <!--  type="text"-->
          <!--  icon="el-icon-error"-->
          <!--  @click="delAccount(scope.row)"-->
          <!--&gt;{{ $t('注销账号') }}</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户管理对话框 -->
    <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <lpBaseForm ref="lpBaseForm" />
    </el-dialog>
    <!-- 开通账户-->
    <el-dialog v-if="openAnAccountOpen" :title="openAnAccountTitle" :visible.sync="openAnAccountOpen" :close-on-click-modal="false" width="45%" :destory-on-close="true" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <lpAccountHome ref="lpAccountHome" />
    </el-dialog>
    <!-- 导入窗口 -->
    <el-dialog :title="$t('导入')" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false">
      <div>
        <el-upload
          ref="upload"
          v-loading="upload.isUploading"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :on-change="handleFileChange"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
            <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
              {{ $t('下载模板') }}
            </el-link>
          </div>
        </el-upload>

        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLpBase, delLpBase, getByLpId, delLpAccount } from '@/api/fund/lpBase/lpBase'
import { getToken } from '@/utils/auth'
import lpBaseForm from './lpBaseForm.vue'
import lpAccountHome from '@/views/fund/lpBase/lpAccountHome.vue'
export default {
  components: {
    lpBaseForm,
    lpAccountHome
  },
  props: {
    code: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 客户管理表格数据
      lpBaseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      formOpen: false,
      // 查询参数
      queryParams: {
        name: undefined,
        shortName: undefined,
        accountOpen: undefined,
        type: undefined,
        level: undefined,
        followLevel: undefined,
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 出资人导入参数
      upload: {
        // 是否显示弹出层（项目导入）
        open: false,
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/base/lpBase/importData'
      },
      // 客户类型字典
      typeOptions: [],
      // 关注等级字典
      followLeve: [],
      openAnAccountTitle: this.$t('LP账户'),
      emailDisableEmail: undefined,
      openAnAccountOpen: false,
      ruleForm: {
        email: '',
        password: '',
        confirmPassword: '',
        status: '',
        menu: ''
      }
    }
  },
  computed: {
    groupId() { // 获取项目名称
      return new Set(this.lpBaseList.map(o => o.id))
    }
  },
  created() {
    this.getDicts('lp_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('czr_follow_level').then(response => {
      this.followLeve = response.data
    })
    this.getList()
  },
  methods: {
    /** 查询客户管理列表 */
    getList() {
      this.loading = true
      this.queryParams.status = this.code
      listLpBase(this.queryParams).then(response => {
        this.lpBaseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 类型字典回显
    typeFormat(row) {
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        shortName: undefined,
        phone: undefined,
        email: undefined,
        type: undefined,
        level: undefined,
        documentType: undefined,
        certificateId: undefined,
        address: undefined,
        payBankAccountName: undefined,
        payBankAccount: undefined,
        openBack: undefined,
        branch: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        followLeve: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.title = this.$t('客户管理')
      this.$nextTick(() => {
        this.$refs.lpBaseForm.$refs.form.clearValidate()
        this.$refs.lpBaseForm.init(null)
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.title = this.$t('客户管理')
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.lpBaseForm.$refs.form.clearValidate()
        this.$refs.lpBaseForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delLpBase(row.id)
      }).then((res) => {
        if (res.data > 0) {
          this.getList()
          this.msgSuccess(this.$t('删除成功'))
        } else {
          this.$message({
            type: 'warning',
            message: this.$t('当前客户已出资过基金,禁止删除')
          })
        }
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      this.downLoadExcel('/base/lpBase/export', this.queryParams)
    },
    // 现有客户导出
    exportHandleNow() {
      this.downLoadExcel('/base/lpBase/exportNow', this.queryParams)
    },
    // 打开账户页面
    openAnAccount(row) {
      this.openAnAccountOpen = true
      this.$nextTick(() => {
        this.$refs.lpAccountHome.init(row)
      })
    },
    // 删除账户
    delAccount(row) {
      var that = this
      this.$confirm(this.$t('是否注销账号?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        getByLpId(row.id).then(response => {
          if (response.code === 200) {
            if (response.data !== null) {
              delLpAccount(row.id).then(() => {
                that.msgSuccess(that.$t('注销成功!'))
              })
            } else {
              that.msgInfo(that.$t('先创建账户才能执行注销操作!'))
            }
          }
        })
      }).then(() => {
        this.getList()
      })
    },
    dealLen(name) {
      const tmp = Array.from(this.groupId)
      const index = tmp.indexOf(name)
      let len = 0
      for (let i = 0; i < index; i++) {
        len += this.dealGroup(tmp[i])
      }
      return len
    },
    dealGroup(name) {
      return this.lpBaseList.filter(o => o.id === name).length
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if (response.msg === 'success') {
        this.msgSuccess(this.$t('导入成功'))
      } else if (response.code === 500) {
        this.msgError(response.msg)
      } else {
        this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      }
      // this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    },
    // 文件上传变更时间
    handleFileChange(file, fileList) {
      if (!(file.name.indexOf('xls') >= 0 && file.name.indexOf('xlsx') >= 0)) {
        this.msgError(this.$t('仅允许导入“xls”或“xlsx”格式文件！'))
        fileList.splice(0, 1)
      }
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      // 根据项目类型下载不同的模板
      var templateRoute = '/template/investorImportTemplate.xlsx'
      if (templateRoute !== '') {
        window.location.href = url + templateRoute
      }
    }

  }
}
</script>
<style scoped lang="scss">

table{
  border-collapse: collapse;
  border: 0 solid #dfe6ec;
}
table td {
  border-top: 0;
  /*border-bottom: 1px solid #dfe6ec;*/
  border-left: 0;
}
table tr.lastrow td {
  border-bottom: 0;
}

.multi-table-td {
  padding: 7px 0;
  margin: 0 -10px;
  div{
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 0 10px;
  }
  &:first-child{
    padding-top: 0;
  }
  &:last-child{
    border: 0px!important;
    padding-bottom: 0;
  }
}
.noStyle{
  padding: 0px;
}
</style>
